

#include "client.h"
#include <socket/socket.h>
#include <iostream>
#include <fstream>

namespace{

    int Hello(net::Channel& socket)
    {
        char buff[256];
        int nsize = 0;

        try
        {
            const auto nsize = socket.Recv(&buff[0], sizeof(buff) - 1);
            if(nsize == 0)
                return false;

            buff[nsize]=0;
            std::cout<<"from server: "<< buff <<std::endl;
            return std::stoi(buff);
        }
        catch(const std::exception& e)
        {
            std::cout<< e.what()<<std::endl;
            return 0;
        }
    }

    bool SendData(net::Channel& socket, const std::string& data)
    {
        size_t nsize = data.length();
        try
        {
            do
            {
                nsize -= Send(socket, data.c_str(), data.length());
            } while(nsize!=0);
            
            return true;
        }
        catch(const std::exception& e)
        {
            std::cout<< e.what()<<std::endl;
            return false;
        }
    }

    

    

}//namespace


Client::Client()
{
    net::Init();
}

Client::~Client()
{
    net::Shutdown();
}

void Client::Start(const std::string& addr,const std::string& port,
        const std::string& filename)
{
    std::cout<<"Transmission: "<< filename <<std::endl;

    std::ifstream ff(filename, std::ios::binary | std::ios::in);
    if(!ff)
        return std::cout << "ERROR: file not found\n",
            void();

    try
    {
        net::Channel socket;
        socket.Connect(addr, port);

        const auto session = Hello(socket);
        std::cout<<"session: "<< session<<std::endl;
        if(session == 0)
            return std::cout<<"failed\n",
                void();

        SendData(socket, filename);


        ff.seekg(0, std::ios::end);
        const auto size = static_cast<unsigned long>(ff.tellg());
        std::cout<<"size of file = "<<size<<std::endl;

        ff.seekg(0, std::ios::beg);

        std::string datasize(  (char*)&size, ((char*)&size+sizeof(unsigned long))  );

        SendData( socket, datasize );

         
        std::string buffer;
        const size_t capacity = 256;
        buffer.reserve(capacity);
        buffer.resize(capacity, 0);
        while(!ff.eof()) 
        {
            ff.read(&buffer[0], capacity);
            if(!SendData( socket, buffer ))
                return;
        }

    }
    catch(const std::exception& e)
    {
        std::cout<< e.what()<<std::endl;
    }
    
}



